//
//  WBOAuthViewController.swift
//  DLSwift微博
//
//  Created by 丁浪涛 on 2016/11/15.
//  Copyright © 2016年 丁浪涛. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBOAuthViewController: UIViewController {
    
    private lazy var  webView = UIWebView()
    
    override func  loadView()
    {
        view = webView
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        //设置导航栏
        title = "登录新浪微博"
        //按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(tite: "返回", fontSize: 14, target: self, action: #selector(close), isBackButton: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(tite: "自动填充", target: self, action: #selector(atuoFill))
    }
    
    override func  viewDidLoad() {
        super.viewDidLoad()
        let  urlString  = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        
        guard  let url = URL(string: urlString)
            else
        {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        webView.delegate = self
    }
    
    @objc fileprivate func close()
    {
       SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充  -webView的注入 用户名和密码
    
    @objc private func atuoFill()
    {
        let js = "document.getElementById('userId').value = 'dinglang_tao@sina.com'; " +
        "document.getElementById('passwd').value = 'jiayoubb2012';"
        //让webView 执行 Js
        webView.stringByEvaluatingJavaScript(from: js);
        
    }
    
    
}
extension WBOAuthViewController:UIWebViewDelegate
{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //  加载请求 ---Optional("http://baidu.com/?code=61492b6e6201b0ad9c165bda1f95788b")
        //  加载请求 ---Optional("https://m.baidu.com/?from=1012883p")
        //  取消授权 如果请求地址包含(http://baidu.com)不加载
        
        //    3 如果有表示授权成功 否则授权失败
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURL) == false {
            return true
        }
        
        print("加载请求 ---\(request.url?.absoluteString)")
        //quary就是URL 中 ‘？’号后面的
        print("加载请求 ---\(request.url?.query)")
        
        //    2 从http://www.baidu.com 回调地址中查找code=
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        
        
        //从query中获取授权码
        let  code =     request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("获取授权码 \(code)")
        WBNetWorkManager.shared.loadAccessToken(code: code, completion:{ (issuccess) in
            if !issuccess
            {
            SVProgressHUD.showInfo(withStatus: "网络请求失败")
            
            }
            else
            {
                SVProgressHUD.showInfo(withStatus: "登录成功")
              
                //跳转
                //1>通知
                NotificationCenter.default.post(name:  NSNotification.Name(WBUserLoginSuccessNotification), object: nil)
                //关闭窗口
                self.close()
            
            }
        
        
        })
        return false
    }
    
    func  webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func  webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
